<template>
  <div class="data-source-container">
    <div class="toolbar">
      <el-button type="primary" @click="handleCreateDataSource">
        <el-icon><Plus /></el-icon>新建数据源
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索数据源名称"
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <el-table :data="dataSourceList" style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="数据源名称" />
      <el-table-column prop="type" label="类型">
        <template #default="{ row }">
          <el-tag>{{ row.type }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="host" label="主机地址" />
      <el-table-column prop="port" label="端口" width="100" />
      <el-table-column prop="status" label="连接状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? "已连接" : "未连接" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleTest(row)"
              :loading="row.testing"
            >
              测试连接
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <DataSourceForm
      v-model:visible="formVisible"
      :edit-data="editingData"
      @submit="handleFormSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { Plus, Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DataSourceForm from "./components/DataSourceForm.vue";
import {
  getDataSourceList,
  createDataSource,
  updateDataSource,
  deleteDataSource,
  testDataSourceConnection,
} from "@/api/dataSource";
import type { DataSource, DataSourceQuery } from "@/types/dataSource";

const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);
const formVisible = ref(false);
const editingData = ref<DataSource | null>(null);
const dataSourceList = ref<DataSource[]>([]);

const handleCreateDataSource = () => {
  editingData.value = null;
  formVisible.value = true;
};

const handleEdit = (row: any) => {
  editingData.value = row;
  formVisible.value = true;
};

const handleTest = async (row: any) => {
  row.testing = true;
  try {
    // TODO: 实现测试连接逻辑
    await new Promise((resolve) => setTimeout(resolve, 1000));
    ElMessage.success("连接测试成功");
  } catch (error) {
    ElMessage.error("连接测试失败");
  } finally {
    row.testing = false;
  }
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm("确定要删除该数据源吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // TODO: 实现删除数据源逻辑
    ElMessage.success("删除成功");
  });
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  // TODO: 重新加载数据
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  // TODO: 重新加载数据
};

const handleFormSubmit = async (data: any) => {
  loading.value = true;
  try {
    if (data.id) {
      // TODO: 调用更新接口
      ElMessage.success("更新成功");
    } else {
      // TODO: 调用创建接口
      ElMessage.success("创建成功");
    }
    // TODO: 重新加载数据列表
  } finally {
    loading.value = false;
  }
};

const loadData = async () => {
  loading.value = true;
  try {
    const params: DataSourceQuery = {
      keyword: searchQuery.value,
      page: currentPage.value,
      pageSize: pageSize.value,
    };
    const { list, total: totalCount } = await getDataSourceList(params);
    dataSourceList.value = list;
    total.value = totalCount;
  } catch (error) {
    console.error("加载数据源列表失败:", error);
  } finally {
    loading.value = false;
  }
};

watch([searchQuery, currentPage, pageSize], () => {
  loadData();
});

const handleFormSubmit = async (data: DataSource) => {
  loading.value = true;
  try {
    if (data.id) {
      await updateDataSource(data.id, data);
      ElMessage.success("更新成功");
    } else {
      await createDataSource(data);
      ElMessage.success("创建成功");
    }
    loadData();
  } finally {
    loading.value = false;
  }
};

const handleDelete = (row: DataSource) => {
  if (!row.id) return;

  ElMessageBox.confirm("确定要删除该数据源吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loading.value = true;
    try {
      await deleteDataSource(row.id);
      ElMessage.success("删除成功");
      loadData();
    } finally {
      loading.value = false;
    }
  });
};

const handleTest = async (row: DataSource) => {
  if (!row.id) return;

  row.testing = true;
  try {
    const { success, message } = await testDataSourceConnection(row.id);
    if (success) {
      ElMessage.success("连接测试成功");
    } else {
      ElMessage.error(message || "连接测试失败");
    }
  } catch (error) {
    console.error("测试连接失败:", error);
  } finally {
    row.testing = false;
  }
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.data-source-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 